package backend

import (
	mapset "github.com/deckarep/golang-set/v2"

	"github.com/GoAdminGroup/go-admin/modules/logger"

	"app/models"
	"app/utils"

	jsoniter "github.com/json-iterator/go"
)

func Loop(ID []*int) {
	var sowingIDs, sowedIDs, paymentIDs []int
	var err error
	// 订单状态是待播种,或者有预计播种日期,但是无实际播种日期
	err = models.Orm.Table("orders").
		Select("id").
		Where("order_status = ? OR (estimated_sowing_date <> '' AND actual_sowing_date = '')", 2).
		Pluck("id", &sowingIDs).Error

	if err != nil {
		logger.Error(err)
		return
	}
	// 订单状态是待出苗,或者有预计出苗日期,但是无实际出苗日期
	err = models.Orm.Table("orders").
		Select("id").
		Where("order_status = ? OR (estimated_seedling_date <> '' AND actual_seedling_date = '')", 8).
		Pluck("id", &sowedIDs).Error

	if err != nil {
		logger.Error(err)
		return
	}
	// 订单状态已出苗和待收款
	err = models.Orm.Table("orders o").
		Select("o.id").
		Joins("LEFT JOIN (SELECT order_id, SUM(amount) AS total_payment FROM payment_record GROUP BY order_id) p ON o.id = p.order_id").
		Where("o.order_status in (?)", []int{9, 10}).
		Pluck("id", &paymentIDs).Error

	if err != nil {
		logger.Error(err)
		return
	}
	sowing := len(sowingIDs)
	seedling := len(mapset.NewSet(sowedIDs...).Difference(mapset.NewSet(sowingIDs...)).ToSlice())
	payment := len(mapset.NewSet(paymentIDs...).Difference(mapset.NewSet(sowingIDs...).Union(mapset.NewSet(sowedIDs...))).ToSlice())
	configs, err := LoadConfig(ID)

	if err != nil {
		logger.Error(err)
		return
	}

	for _, config := range configs {
		if err := SendByConfig(config, sowing, seedling, payment); err != nil {
			logger.Error(err)
		}
	}
}

func LoadConfig(ID []*int) ([]*models.SMSConfig, error) {
	var configs []*models.SMSConfig
	base := models.Orm.Model(&models.SMSConfig{}).
		Select("sms_config.*").Where("is_active > 0")
	if len(ID) > 0 {
		base = base.Where("id in (?)", ID)
	}
	base.Find(&configs)
	err := base.Find(&configs).Error
	return configs, err
}

func SendByConfig(config *models.SMSConfig, sowing, seedling, payment int) error {
	sms := &utils.Sms{
		AccessKeyId:     config.AccessKeyID,
		AccessKeySecret: config.AccessKeySecret,
		Scheme:          config.Scheme,
		PhoneNumbers:    config.Phone,
		SignName:        config.Sign,
		TemplateCode:    config.Template,
		TemplateParam: &utils.TemplateParam{
			Phone:    config.Phone,
			Sowing:   sowing,
			Seedling: seedling,
			Payment:  payment,
		},
	}
	result := sms.SendSMS()
	template, _ := jsoniter.Marshal(sms.TemplateParam)
	data := models.SMSRecord{
		SMSRecordCore: models.SMSRecordCore{
			Content: string(template),
			Result:  result,
		},
	}
	res := models.Orm.Create(&data)
	return res.Error
}

func UpdateAccessURL(ID []*int) {
	var tasks []*models.TaskRecord
	base := models.Orm.Model(&models.TaskRecord{})

	if len(ID) > 0 {
		base = base.Where("id in (?)", ID)
	}

	err := base.Find(&tasks).Error
	if err != nil {
		logger.Errorf("find task err:%+v", err)
	}
	for _, task := range tasks {
		if task.OSSUrl == "" {
			continue
		}
		accessURL, err := utils.GetOSSUrl(task.OSSUrl)

		if err != nil || accessURL == "" {
			continue
		}
		task.AccessUrl = accessURL
		models.Orm.Save(task)
		logger.Infof("task access url : %s 更新完成", task.AccessUrl)
	}

}
